//
//  DataModel.swift
//  todoList
//
//  Created by AINI on 2019/2/14.
//  Copyright © 2019 AINI. All rights reserved.
//

import Foundation

class DataModel {
    var lists = [Checklist]()
    
    init() {
      loadChecklists()
      registerDefaults()
      handleFirstTime()
    }
    var indexOfSelectedChecklist: Int {
        get {
            return UserDefaults.standard.integer(forKey: "ChecklistIndex")
        }
        set {
            UserDefaults.standard.set(newValue, forKey: "ChecklistIndex")
            UserDefaults.standard.synchronize()
        }
    }
    func documentsDirectory() -> URL {
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        return paths[0]
    }
    
    func dataFilePath() -> URL {
        return documentsDirectory().appendingPathComponent(
            "Checklists.plist")
    }
    
    func saveChecklists() {
        let data = try! NSKeyedArchiver.archivedData(withRootObject: lists, requiringSecureCoding: false)
        try! data.write(to: dataFilePath())
    }
    
    func loadChecklists() {
        //1 读取文件路径
        let path = dataFilePath()
        // 获取data
        guard  let data = try? Data(contentsOf: path, options: []) else {
            return
        }
        //3解码成数组
        if let unarchiver = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? [Checklist] {
            lists = unarchiver!
        } else {
            return
        }
    }
    func handleFirstTime() {
        let userDefaults = UserDefaults.standard
        let firstTime = userDefaults.bool(forKey: "FirstTime")
        
        if firstTime {
            let checklist = Checklist(name: "List")
            lists.append(checklist)
            
            indexOfSelectedChecklist = 0
            userDefaults.set(false, forKey: "FirstTime")
            userDefaults.synchronize()
        }
    }
        func registerDefaults() {
            let dictionary: [String: Any] = ["ChecklistIndex": -1,"FirstTime": true,"ChecklistItemID": 0]
            UserDefaults.standard.register(defaults: dictionary)
        }
    func sortChecklists() {
        lists.sort(by: {
            checklist1, checklist2 in
            return checklist1.name.localizedStandardCompare(checklist2.name) == .orderedAscending
        })
    }
    class func nextChecklistItemID() -> Int {
        let userDefaults = UserDefaults.standard
        let itemID = userDefaults.integer(forKey: "ChecklistItemID")
        userDefaults.set(itemID + 1, forKey: "ChecklistItemID")
        userDefaults.synchronize()
        return itemID
    }
}
